package com.dhcc.bpm.modules.workflow.service.impl;

import com.dhcc.bpm.common.enums.ConfigType;
import com.dhcc.bpm.common.json.JSONObject;
import com.dhcc.bpm.common.redisMessage.RedisMessageSender;
import com.dhcc.bpm.common.utils.DateUtils;
import com.dhcc.bpm.modules.api.entity.Api;
import com.dhcc.bpm.modules.api.entity.IssueApi;
import com.dhcc.bpm.modules.api.entity.Product;
import com.dhcc.bpm.modules.api.entity.ProductApi;
import com.dhcc.bpm.modules.api.service.*;
import com.dhcc.bpm.modules.api.vo.productListVo;
import com.dhcc.bpm.modules.common.entity.Plupload;
import com.dhcc.bpm.modules.common.service.IPluploadService;
import com.dhcc.bpm.modules.content.entity.DocDirectory;
import com.dhcc.bpm.modules.content.service.IDocDirectoryService;
import com.dhcc.bpm.modules.content.vo.DocDirectoryVO;
import com.dhcc.bpm.modules.gateway.entity.Gateway;
import com.dhcc.bpm.modules.gateway.service.IGatewayRouteService;
import com.dhcc.bpm.modules.gateway.service.IGatewayService;
import com.dhcc.bpm.modules.orga.entity.*;
import com.dhcc.bpm.modules.orga.service.*;
import com.dhcc.bpm.modules.orga.vo.AppVO;
import com.dhcc.bpm.modules.orga.vo.ProduceApplyVO;
import com.dhcc.bpm.modules.sandbox.entity.SandboxApi;
import com.dhcc.bpm.modules.sandbox.entity.SandboxCase;
import com.dhcc.bpm.modules.sandbox.service.ISandboxApiService;
import com.dhcc.bpm.modules.sandbox.service.ISandboxCaseService;
import com.dhcc.bpm.modules.system.service.ISerialNumberService;
import com.dhcc.bpm.modules.workflow.dto.ApiBO;
import com.dhcc.bpm.modules.workflow.dto.ProcessStartDto;
import com.dhcc.bpm.modules.workflow.dto.TaskCommitDto;
import com.dhcc.bpm.modules.workflow.dto.TaskDto;
import com.dhcc.bpm.modules.workflow.entity.WorkOrder;
import com.dhcc.bpm.modules.workflow.mapper.ApproveMapper;
import com.dhcc.bpm.modules.workflow.service.IWorkFlowService;
import com.dhcc.bpm.modules.workflow.service.IWorkOrderService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @ClassName WorkFlowServiceImpl
 * @Description 工作流实现方法
 * @Author xiafayu
 * @Date 2020/2/21 0021 15:16
 * @Version V1.0
 * @Copyright: 2020 东华软件 . All rights reserved.
 **/
@Service
public class WorkFlowServiceImpl implements IWorkFlowService {

    private static final Logger log = LoggerFactory.getLogger(WorkFlowServiceImpl.class);
    @Value("${bpm.approval.isApproval}")
    boolean isApproval;
    @Autowired
    private IPluploadService pluploadService;
    @Autowired
    ApproveMapper approveMapper;
    @Autowired
    private IBackserviceService backserviceService;
    @Autowired
    private ISandboxApiService sandboxApiService;
    @Autowired
    private IProductApiService productApiService;
    @Autowired
    private IOrgaService orgaService;
    @Autowired
    private IAppService appService;
    @Autowired
    private IApiService apiService;
    @Autowired
    private ITestApplyService testApplyService;
    @Autowired
    private IProduceApplyService produceApplyService;
    @Autowired
    private IOnlineApplyService onlineApplyService;
    @Autowired
    private IProductService productService;
    @Autowired
    private IDocDirectoryService iDocDirectoryService;
    @Autowired
    private ISandboxCaseService iSandboxCaseService;
    @Autowired
    private IIssueApiService issueApiService;
    @Autowired
    private IGatewayRouteService gatewayRouteService;
    @Autowired
    private IAppApiService appApiService;
    @Autowired
    private IWorkOrderService workOrderService;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    private RedisMessageSender redisMessageSender;
    @Autowired
    private TokenStore tokenStore;
    @Value("${workflow.base-url}")
    String workflow_base_url;
    @Autowired
    private ISerialNumberService serialNumberService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IGatewayService gatewayService;
    private static final String EXP_SQE = "expSeq";

    /**
     * @param taskCommitDto
     * @return com.dhcc.bpm.common.json.JSONObject
     * @throws
     * @Description 提交
     * @Author xiafayu
     * @Date 2020/2/24 20:43
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject commit(TaskCommitDto taskCommitDto) {
        JSONObject resp = null;
        try {
            resp = restTemplate.postForObject(workflow_base_url + "/api/workflow/task/commit", taskCommitDto, JSONObject.class);
            log.info("工作流审批响应结果：{}", resp);
        } catch (Exception e) {
            log.error("发起审批异常：{}", e);
            return resp;
        }

        List<String> ids = taskCommitDto.getApiIds();
        if (resp != null && resp.getInt("code") == 200) {

            JSONObject data = resp.getObj("data");
            Boolean endSts = data.getBool("endSts");
            String appId = data.getStr("appId");
            String opinionType = data.getStr("opinionType");
            char type = appId.charAt(0);
            String app_id = appId.substring(1);
            resp.put("id", app_id);
            try {
                //如果非最终节点
                if (!endSts) {
                    if (type == 'a') {
                        productPublishNotEnd(ids, data, opinionType, app_id);
                    } else if (type == 'c') {
                        channelCreateNotEnd(ids, data, opinionType, app_id);
                    } else if (type == 'w') {
                        //更新工单状态
                        WorkOrder workOrder = workOrderService.getById(app_id);
                        workOrder.setOpinion(taskCommitDto.getApprovalOpinion());
                        workOrder.setStatus(0);
                        workOrder.setIsDispatch("1");
                        workOrderService.saveOrUpdate(workOrder);
                    }
                }
                //审批不同意填写意见，重新发起审批不填写意见，还能显示意见
                String approveOpinion = taskCommitDto.getApprovalOpinion();
                if (null == approveOpinion) {
                    approveOpinion = "";
                }
                //如果是最终节点
                if (endSts) {
                    if (type == 'a') {
                        productPublish(ids, data, opinionType, app_id);
                        resp.put("type", "prod");
                    } else if (type == 'i') {
                        orgAccreditation(data, opinionType, app_id, approveOpinion);
                        resp.put("type", "orga");
                    } else if (type == 'c') {
                        channelCreate(ids, data, opinionType, app_id, approveOpinion);
                        resp.put("type", "chnl");
                    } else if (type == 'k') {
                        orgAccreditationChange(data, opinionType, app_id, approveOpinion);
                        resp.put("type", "orga");
                    } else if (type == 'm') {
                        produceApply(data, opinionType, app_id, approveOpinion);
                        resp.put("type", "produceApply");
                    } else if (type == 'n') {
                        onlineApply(data, opinionType, app_id, approveOpinion);
                        resp.put("type", "onlineApply");
                    } else if (type == 'p') {
                        App newApp = appService.getById(app_id);
                        channelCreateChange(data, opinionType, app_id, newApp, approveOpinion);
//                    // 通知网关刷新token
//                    refreshToken(newApp.getTestAppId());
//                    refreshToken(newApp.getAppId());
                        resp.put("type", "chnl");
                    } else if (type == 'b') {
                        apiPublish(data, opinionType, app_id);
//                    // 通知网关刷新api配置
//                    refreshApi();
                        resp.put("type", "api");
                    } else if (type == 'z') {
                        productOffline(data, opinionType, app_id);
                        resp.put("type", "prod");
                    } else if (type == 'y') {
                        apiOffline(data, opinionType, app_id);
//                    // 通知网关刷新api
//                    refreshApi();
                        resp.put("type", "api");
                    } else if (type == 'x') {
                        produceApplyChange(data, opinionType, app_id, approveOpinion);
                        resp.put("type", "produceApply");
                    } else if (type == 'w') {
                        //更新工单状态
                        WorkOrder workOrder = workOrderService.getById(app_id);
                        workOrder.setStatus(1);
                        workOrder.setOpinion(approveOpinion);

                        resp.put("type", "workOrder");
                        boolean bool = false;
                        if (!endSts) {
                            bool = true;
                            workOrder.setStatus(0);
                        }
                        resp.put("endSts", bool);
                        workOrderService.saveOrUpdate(workOrder);
                    }
                }
            } catch (Exception e) {
                log.error("工作流提交后处理异常：", e);
                JSONObject resp2 = new JSONObject();
                //工作流正常，后续处理异常，再次发起审批并提示前台检查数据
                ProcessStartDto processStartDto = new ProcessStartDto();
                processStartDto.setAppId(appId);
                switch (type) {
                    case 'a':
                        processStartDto.setProcessKey("product_publish");
                        resp2.put("type", "prod");
                        break;
                    case 'i':
                        processStartDto.setProcessKey("org_accreditation");
                        resp2.put("type", "orga");
                        break;
                    case 'c':
                        processStartDto.setProcessKey("channel_create");
                        resp2.put("type", "chnl");
                        break;
                    case 'k':
                        processStartDto.setProcessKey("org_accreditation_change");
                        resp2.put("type", "orga");
                        break;
                    case 'm':
                        processStartDto.setProcessKey("produce_apply");
                        resp2.put("type", "produceApply");
                        break;
                    case 'n':
                        processStartDto.setProcessKey("online_apply");
                        resp2.put("type", "onlineApply");
                        break;
                    case 'p':
                        processStartDto.setProcessKey("channel_create_change");
                        resp2.put("type", "chnl");
                        break;
                    case 'b':
                        processStartDto.setProcessKey("api_publish");
                        resp2.put("type", "api");
                        break;
                    case 'z':
                        processStartDto.setProcessKey("product_offline");
                        resp2.put("type", "prod");
                        break;
                    case 'y':
                        processStartDto.setProcessKey("api_offline");
                        resp2.put("type", "api");
                        break;
                    default:
                        break;
                }
                Map<String, Object> map = new HashMap<>();
                map.put("params", "");
                processStartDto.setWfParm(map);
                List<Long> ids2 = new ArrayList();
                ids2.add(Long.valueOf(app_id));
                processStartDto.setIds(ids2);
                BladeUser user = AuthUtil.getUser();
                processStartDto.setUserId(user.getUserId().toString());
                JSONObject resJson = start(processStartDto);
//                resp2.put("exception", "检查数据是否有误导致审批失败");
                resp2.put("id", app_id);
                resp2.put("code", 500);
                return resp2;
            }

        }
        return resp;
    }

    @Transactional(rollbackFor = Exception.class)
    public void channelCreateNotEnd(List<String> ids, JSONObject data, String opinionType, String app_id) {
        //应用创建
        App app = appService.getById(Long.parseLong(app_id));
        app.setStatus(Integer.parseInt(opinionType));
        //非最终节点只更新渠道信息的API状态，不更新渠道状态
        //全部API
        if (ids == null || ids.size() <= 0) {
            switch (opinionType) {
                case "1":
                    //如果审批通过
                    if (appService.updateOpc_app_api(Long.parseLong(app_id), opinionType) > 0) {
                        data.put("code", 200);
                        data.put("msg", "审批成功");
                    } else {
                        data.put("code", 500);
                        data.put("msg", "审批失败");
                    }
                    break;
                case "2":
                    //如果审批未通过
                    if (appService.updateById(app) && appService.updateOpc_app_api(Long.parseLong(app_id), opinionType) > 0) {
                        data.put("code", 200);
                        data.put("msg", "审批成功");
                    } else {
                        data.put("code", 500);
                        data.put("msg", "审批失败");
                    }
                    break;
                default:
                    break;
            }
        } else {
            //部分API，因为传了API信息，所以审批必定通过
            AppApi appApi = new AppApi();
            appApi.setOpcAppId(Long.parseLong(app_id));
            appApi.setValidStatus(opinionType);
            Map<Long, Object> condition = new HashMap<Long, Object>();
            int i = 0;
            for (String api_id : ids) {
                appApi.setOpcApiId(Long.parseLong(api_id));
                i += appService.updateSingleOpc_app_api(appApi);
                condition.put(Long.parseLong(api_id), "");
            }
            // 更新未通过api状态
            List<AppApi> appApis = appService.listRelatedApi(Long.parseLong(app_id));
            for (AppApi api : appApis) {
                if (null == condition.get(api.getId())) {
                    api.setValidStatus("2");
                    appService.updateSingleOpc_app_api(api);
                }
            }
            if (i >= ids.size()) {
                data.put("code", 200);
                data.put("msg", "审批成功");
            } else {
                data.put("code", 500);
                data.put("msg", "审批失败");
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void productPublishNotEnd(List<String> ids, JSONObject data, String opinionType, String app_id) {
        //产品API关联
        ProductApi productApi = new ProductApi();
        productApi.setProductId(Long.parseLong(app_id));
        productApi.setStatus(Integer.parseInt(opinionType));
        if (ids == null || ids.size() <= 0) {
            //如果不传，有可能是通过或拒绝
            if (productApiService.updateAllStatus(productApi) > 0) {
                data.put("code", 200);
                data.put("msg", "审批成功");
            } else {
                data.put("code", 500);
                data.put("msg", "审批失败");
            }
        } else {
            //只通过部分
            int i = 0;
            for (String api_id : ids) {
                productApi.setApiId(Long.parseLong(api_id));
                i += productApiService.updateStatus(productApi);
            }
            if (i >= ids.size()) {
                data.put("code", 200);
                data.put("msg", "审批成功");
            } else {
                data.put("code", 500);
                data.put("msg", "审批失败");
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void productPublish(List<String> ids, JSONObject data, String opinionType, String app_id) {
        //更新产品发布状态
        Product prods = new Product();
        prods.setId(Long.parseLong(app_id));
        prods.setStatus(Integer.parseInt(opinionType));
        prods.setIsDeleted(0);
        productService.updateById(prods);
        //产品API关联
        ProductApi productApi = new ProductApi();
        productApi.setProductId(Long.parseLong(app_id));
        productApi.setStatus(Integer.parseInt(opinionType));
        productApi.setIsDeleted(0);
        if (ids == null || ids.size() <= 0) {

            //审批通过, 生成文档目录
            if (opinionType.equals("1")) {
                Product product = productService.getById(Long.parseLong(app_id));
                //审批通过, 生成文档目录
                DocDirectory docDirectory = new DocDirectory();
                docDirectory.setRelateId(product.getId().toString());
                docDirectory.setDocName(product.getProductName());
                docDirectory.setDocCode(product.getProductCode());
                docDirectory.setParentId("0");
                docDirectory.setUrl("#");
                docDirectory.setDocType("2");
                docDirectory.setDescribe(product.getDescribe());
                docDirectory.setStatus(1);
//                DocDirectory isNull = iDocDirectoryService.getOne(Condition.getQueryWrapper(docDirectory));
                DocDirectory isNull = iDocDirectoryService.findByDocCode(docDirectory);
                // 表中已存在产品信息则不再插入
                if (isNull == null) {
                    iDocDirectoryService.save(docDirectory);
                }
                // 产品Api接口信息集
                List<ApiBO> apiBOS = productApiService.listRelatedApi(Long.parseLong(app_id));
                for (ApiBO apiBO : apiBOS) {
                    DocDirectory docApi = iDocDirectoryService.findByDocCode(apiBO.getApiCode(), product.getProductCode(), apiBO.getId());
                    if (docApi == null) {
                        docApi = new DocDirectory();
                    }
                    docApi.setDocCode(apiBO.getApiCode());
                    docApi.setParentId(product.getProductCode());
                    docApi.setDocName(apiBO.getApiName());
                    docApi.setUrl("");
                    docApi.setOriginalPath("");
                    if (apiBO.getBusId() != null) {
                        Plupload plupload = pluploadService.selectById(apiBO.getBusId());
                        if (plupload != null) {
                            docApi.setUrl(plupload.getFileFullpath());
                            docApi.setOriginalPath(plupload.getOriginalPath());
                        }
                    }
                    docApi.setRelateId(apiBO.getId());
                    docApi.setDocType("3");
                    docApi.setDescribe(apiBO.getDescribe());
                    docApi.setStatus(1);
                    iDocDirectoryService.saveOrUpdate(docApi);
                }
            }

            if (productApiService.updateAllStatus(productApi) > 0) {
                data.put("code", 200);
                data.put("msg", "审批成功");
            } else {
                data.put("code", 500);
                data.put("msg", "审批失败");
            }
        } else {
            int i = 0;
            Map<String, Object> condition = new HashMap<String, Object>();
            for (String api_id : ids) {
                productApi.setApiId(Long.parseLong(api_id));
                i += productApiService.updateStatus(productApi);
                condition.put(api_id, "");
            }
            ProductApi proApi = new ProductApi();
            proApi.setProductId(Long.parseLong(app_id));
            proApi.setStatus(null);
            List<ProductApi> productApis = productApiService.listProductApi(proApi);
            // 更新未通过api状态
            for (ProductApi api : productApis) {
                if (null == condition.get(String.valueOf(api.getApiId()))) {
                    api.setStatus(2);
                    productApiService.updateStatus(api);
                }
            }
            if (i >= ids.size()) {
                //审批通过
                if (opinionType.equals("1")) {
                    Product product = productService.getById(Long.parseLong(app_id));
                    DocDirectory docDirectory = new DocDirectory();
                    docDirectory.setDocName(product.getProductName());
                    docDirectory.setDocCode(product.getProductCode());
                    docDirectory.setParentId("0");
                    docDirectory.setUrl("#");
                    docDirectory.setDocType("2");
                    docDirectory.setDescribe(product.getDescribe());
                    docDirectory.setStatus(1);
                    DocDirectory isNull = iDocDirectoryService.getOne(Condition.getQueryWrapper(docDirectory));
                    // 表中已存在产品信息则不再插入
                    if (isNull == null) {
                        iDocDirectoryService.save(docDirectory);
                    }
                    // 产品Api接口信息集
                    List<ApiBO> apiBOS = productApiService.listRelatedApi((Long.parseLong(app_id)));
                    for (ApiBO api : apiBOS) {
                        if (null != condition.get(api.getId())) {
                            DocDirectory docApi = new DocDirectory();
                            docApi.setDocCode(api.getApiCode());
                            docApi.setParentId(product.getProductCode());
                            docApi.setDocName(api.getApiName());
                            docApi.setUrl("");
                            docApi.setOriginalPath("");
                            if (api.getBusId() != null) {
                                Plupload plupload = pluploadService.selectById(api.getBusId());
                                if (plupload != null) {
                                    docApi.setUrl(plupload.getFileFullpath());
                                    docApi.setOriginalPath(plupload.getOriginalPath());
                                }
                            }
                            docApi.setDocType("3");
                            docApi.setDescribe(api.getDescribe());
                            docApi.setStatus(1);
                            iDocDirectoryService.save(docApi);
                        }
                    }
                }
                data.put("code", 200);
                data.put("msg", "审批成功");
            } else {
                data.put("code", 500);
                data.put("msg", "审批失败");
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void apiOffline(JSONObject data, String opinionType, String app_id) {
        // API 下线
        Api api = new Api();
        api.setId(Long.parseLong(app_id));
        if (opinionType.equals("1")) {
            // 审批通过
            api.setStatus(6);
            boolean updated = apiService.updateById(api);
            if (updated) {
                data.put("code", 200);
                data.put("msg", "审批成功");
            } else {
                data.put("code", 500);
                data.put("msg", "审批失败");
            }
        } else {
            // 审批失败
            api.setStatus(1);
            boolean updated = apiService.updateById(api);
            if (updated) {
                data.put("code", 200);
                data.put("msg", "审批成功");
            } else {
                data.put("code", 500);
                data.put("msg", "审批失败");
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void productOffline(JSONObject data, String opinionType, String app_id) {
        // 产品下线
        Product productQuery = new Product();
        productQuery.setId(Long.parseLong(app_id));
        Product product = new Product();
        ProductApi productApi = new ProductApi();
        productApi.setProductId(Long.parseLong(app_id));
        if (opinionType.equals("1")) {
            // 审批通过
            product = productService.getOne(Condition.getQueryWrapper(productQuery));
            // 更新 opc_product
            product.setStatus(6);
//                        product.setIsDeleted(1);
            boolean proUpdated = productService.updateById(product);
            // 更新 opc_product_api
            productApi.setStatus(9);
//                        productApi.setIsDeleted(1);
            int apiUpdated = productApiService.updateAllStatus(productApi);
            // 更新 opc_doc_directory
//                        iDocDirectoryService.removeDocByProductCode(product.getProductCode());
            iDocDirectoryService.updateDocByProductCode(product.getProductCode());
            if (proUpdated & apiUpdated != 0) {
                data.put("code", 200);
                data.put("msg", "审批成功");
            } else {
                data.put("code", 500);
                data.put("msg", "审批失败");
            }
        } else {
            // 审批拒绝
            product.setId(Long.parseLong(app_id));
            product.setStatus(1);
            boolean updated = productService.updateById(product);
            productApi.setStatus(1);
            int apiUpdated = productApiService.updateApiStatus(productApi);
            if (updated & apiUpdated != 0) {
                data.put("code", 200);
                data.put("msg", "审批成功");
            } else {
                data.put("code", 500);
                data.put("msg", "审批失败");
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void apiPublish(JSONObject data, String opinionType, String app_id) {
        // API 审批
//                    Api api = new Api();
//                    api.setId(Long.parseLong(app_id));
//                    if (opinionType.equals("1")) {
//                        // 审批通过
//                        api.setStatus(1);
//                        boolean updated = apiService.updateById(api);
//                        if(updated){
//                            data.put("code", 200);
//                            data.put("msg", "审批成功");
//                        }else{
//                            data.put("code", 500);
//                            data.put("msg", "审批失败");
//                        }
//                    }else{
//                        // 审批拒绝
//                        api.setStatus(2);
//                        boolean updated = apiService.updateById(api);
//                        if(updated){
//                            data.put("code", 200);
//                            data.put("msg", "审批成功");
//                        }else{
//                            data.put("code", 500);
//                            data.put("msg", "审批失败");
//                        }
//                    }
        Api apiDoc = apiService.getById(app_id);
        if (apiDoc.getBusId() != null) {
            List<DocDirectoryVO> docList = iDocDirectoryService.findByApiCode(apiDoc.getApiCode());
            docList.forEach(docDirectoryVO -> {
                Plupload plupload = pluploadService.selectById(apiDoc.getBusId());
                if (plupload == null) {
                    docDirectoryVO.setFileFullPath(plupload.getFileFullpath());
                    docDirectoryVO.setOriginalPath(plupload.getOriginalPath());
                    docDirectoryVO.setStatus(1);
                    iDocDirectoryService.saveOrUpdate(docDirectoryVO);
                }
            });
        }


        // 更新中间表
        IssueApi issueApiQuery = new IssueApi();
        issueApiQuery.setId(Long.parseLong(app_id));
        List<IssueApi> issueApis = issueApiService.selectByCondition(issueApiQuery);
        Map<String, Boolean> records = new HashMap<>();
        // 更新api审批结果
        Api api = new Api();
        api.setStatus(opinionType.equals("1") ? 1 : 2);
        for (IssueApi issueApi1 : issueApis) {
            api.setId(issueApi1.getApiId());
            boolean updated = apiService.updateById(api);
            if (!updated) {
                records.put("updated", false);
            } else {
//                api = apiService.getById(issueApi1.getApiId());
//                if(api != null){
//                    //生产环境添加路由
//                    GatewayRoute route = gatewayRouteService.getGatewayByApiId(api.getId().toString(), "1");
//                    if(route == null){
//                        route = new GatewayRoute();
//                    }
//                    List<BackserviceVO> backservice = backserviceService.getByBaseProductId(api.getBackserviceId());
//                    String backServiceId = "";
//                    if(backservice.size() >0){
//                        backServiceId = backservice.get(0).getId().toString();
//                    }
//                    // 2020.07.29 路由默认开启
//                    route.setStatus(0);
//                    route.setOpcApiId(api.getId().toString());
////                    route.setBackServiceId(api.getAtomicServiceId().toString());
//                    route.setBackServiceId(backServiceId);
//                    route.setEnv("1");
//                    route.setStatus(0);
//                    route.setOpcGatewayId(api.getOpcGatewayId());
//                    route.setRouteConfig("[{\"predicateValue\":\"" + api.getApiPath() + "\",\"name\":\"Path\"}]");
//                    //路由过滤器
//                    if(api.getBackserviceReqUrl() != null){
//                        route.setFilters("[{\"filterValue\":\"" + api.getBackserviceReqUrl() + "\",\"name\":\"SetPath\"}]");
//                    }
//                    gatewayRouteService.saveOrUpdate(route);
//
//                    // 沙箱环境添加路由
//                    GatewayRoute sandboxRoute = gatewayRouteService.getGatewayByApiId(api.getId().toString(), "2");
//                    if(sandboxRoute == null){
//                        sandboxRoute = new GatewayRoute();
//                    }
//                    // 2020.07.29 路由默认开启
//                    sandboxRoute.setStatus(0);
//                    sandboxRoute.setOpcApiId(api.getId().toString());
////                    sandboxRoute.setBackServiceId(api.getAtomicServiceId().toString());
//                    sandboxRoute.setBackServiceId(backServiceId);
//                    // 环境类型 2:沙箱环境
//                    sandboxRoute.setEnv("2");
//                    sandboxRoute.setStatus(0);
//                    sandboxRoute.setOpcGatewayId(api.getOpcGatewayIdTest());
//                    sandboxRoute.setRouteConfig("[{\"predicateValue\":\"" + api.getApiPathTest() + "\",\"name\":\"Path\"}]");
//                    //路由过滤器
//                    if(api.getBackserviceReqUrl() != null){
//                        sandboxRoute.setFilters("[{\"filterValue\":\"" + api.getBackserviceReqUrl() + "\",\"name\":\"SetPath\"}]");
//                    }
//                    gatewayRouteService.saveOrUpdate(sandboxRoute);
//                }
            }

        }
        if (records.get("updated") == null) {
            data.put("code", 200);
            data.put("msg", "审批成功");
        } else {
            data.put("code", 500);
            data.put("msg", "审批失败");
        }
        issueApiService.updateStatus(Long.parseLong(app_id));
    }

    @Transactional(rollbackFor = Exception.class)
    public void channelCreateChange(JSONObject data, String opinionType, String app_id, App newApp, String approvalOpinion) {
        boolean isChange = false;
        // 应用信息变更
        App oldApp = new App();
        newApp.setApproveOpinion(approvalOpinion);
        if (opinionType.equals("1")) {
            // 审批通过
            // 将变更最新数据copy到旧数据中并更新(下面为前台支持修改的信息)
            oldApp.setId(newApp.getPid());
            oldApp.setDescribe(newApp.getDescribe());
            oldApp.setPerCharge(newApp.getPerCharge());
            oldApp.setPrpTel(newApp.getPrpTel());
            oldApp.setAppType(newApp.getAppType());
            oldApp.setAppValidTime(newApp.getAppValidTime());
            oldApp.setAppState("1");
            oldApp.setApproveOpinion(approvalOpinion);
            //修改问题：变更渠道名称修改审批通过后名称未变更  修改时间：20210514 修改人：xiafayu
            oldApp.setAppName(newApp.getAppName());
            boolean oldUpdated = appService.updateById(oldApp);

            //更新产品api表 20200810 新增条件 validStatus = '1'
            appApiService.deleteByAppId(newApp.getPid(), "2");
            List<AppApi> lists = appApiService.selectByAppId(Long.valueOf(app_id));
            List<AppApi> oldLists = appApiService.selectByAppId(newApp.getPid());
            SandboxCase sanbox = iSandboxCaseService.selectSandboxCaseByAppId(newApp.getPid());
            if (sanbox == null) {
                sanbox = new SandboxCase();
            }
            sanbox.setCaseName(newApp.getAppName() + "案例");
            sanbox.setOpcOrgaId(newApp.getOpcOrgaId());
            sanbox.setOpcAppId(newApp.getPid());
            iSandboxCaseService.modifySandboxCase(sanbox);

            for (AppApi appApi : lists) {
                //改变接口状态
                appApi.setValidStatus("1");
//                //修改app变更后APP没有接口权限  修改时间：20200917 16:10
//                appApi.setOpcAppId(newApp.getPid());
                appApiService.updateById(appApi);

                if (!"3".equals(appApi.getChangeStatus())) {
                    isChange = true;
                }
                //移除状态api的不修改到接入app里面   修改时间：20210706 14:52:22
                if (!"2".equals(appApi.getChangeStatus())) {
                    //修改app变更完成后，变更渠道不显示关联APi  修改时间：20201125 16:33:11
                    AppApi appApiParent = new AppApi();
                    appApiParent.setOpcAppId(newApp.getPid());
                    appApiParent.setValidStatus(appApi.getValidStatus());
                    appApiParent.setNoticeStatus(appApi.getNoticeStatus());
                    appApiParent.setOpcApiId(appApi.getOpcApiId());
                    appApiParent.setOpcProductId(appApi.getOpcProductId());
                    appApiParent.setConfirmStatus(appApi.getConfirmStatus());
                    appApiParent.setNoticeTime(appApi.getNoticeTime());
                    appApiParent.setChangeStatus(appApi.getChangeStatus());
                    appApiParent.setApprovalEnv("2");
                    appApiParent.setExpSeq(stringRedisTemplate.opsForValue().get("expSeq"));
                    appApiService.save(appApiParent);
                    appApiParent = null;

                    SandboxApi sandboxApi = new SandboxApi();
                    sandboxApi.setApiId(appApi.getOpcApiId());
                    sandboxApi.setCaseId(sanbox.getId());
                    sandboxApiService.save(sandboxApi);
                    sandboxApi = null;
                }


            }

            for (AppApi appApi : oldLists) {
                appApi.setValidStatus("1");
//                //修改app变更后APP没有接口权限  修改时间：20200917 16:10
//                appApi.setOpcAppId(newApp.getPid());
                appApiService.updateById(appApi);
                if (!"3".equals(appApi.getChangeStatus())) {
                    isChange = true;
                }
                //移除状态api的不修改到接入app里面   修改时间：20210706 14:52:22
                if (!"2".equals(appApi.getChangeStatus())) {
                    //修改app变更完成后，变更渠道不显示关联APi  修改时间：20201125 16:33:11
                    AppApi appApiParent = new AppApi();
                    appApiParent.setOpcAppId(newApp.getPid());
                    appApiParent.setValidStatus(appApi.getValidStatus());
                    appApiParent.setNoticeStatus(appApi.getNoticeStatus());
                    appApiParent.setOpcApiId(appApi.getOpcApiId());
                    appApiParent.setOpcProductId(appApi.getOpcProductId());
                    appApiParent.setConfirmStatus(appApi.getConfirmStatus());
                    appApiParent.setNoticeTime(appApi.getNoticeTime());
                    appApiParent.setChangeStatus(appApi.getChangeStatus());
                    appApiParent.setApprovalEnv("2");
                    appApiParent.setExpSeq(stringRedisTemplate.opsForValue().get("expSeq"));
                    appApiService.save(appApiParent);
                    appApiParent = null;

                    SandboxApi sandboxApi = new SandboxApi();
                    sandboxApi.setApiId(appApi.getOpcApiId());
                    sandboxApi.setCaseId(sanbox.getId());
                    sandboxApiService.save(sandboxApi);
                    sandboxApi = null;
                }
            }

            if (isApproval) {
                //更新申请测试数据
                //通过覆盖数据
                TestApply test = new TestApply();
                test.setAppId(newApp.getPid());
                TestApply testApplys = testApplyService.getOne(Condition.getQueryWrapper(test));
                testApplys.setTestBeginTime(testApplys.getBeginTimeNew());
                testApplys.setTestEndTime(testApplys.getEndTimeNew());
                testApplys.setApplyQps(Long.valueOf(testApplys.getApplyFlow()));
                testApplys.setApprovalQps(Long.valueOf(testApplys.getApprovalFlow()));
                testApplys.setApproveOpinion(approvalOpinion);
                testApplyService.updateById(testApplys);
            }

            // 更改认证状态
            newApp.setOperationType(2L);
            newApp.setStatus(1);
            boolean newUpdated = appService.updateById(newApp);
            if (oldUpdated & newUpdated) {
                Orga orga = orgaService.getById(newApp.getOpcOrgaId());
                if ("1".equals(orga.getProcessFlag())) {
                    //流程简化开启，直接变更生产环境数据
                    ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
                    lists.forEach(appApi -> {
                        //移除状态api的不修改到接入app里面   修改时间：20210706 14:52:22
                        appApiService.deleteByAppId(newApp.getPid(), "1");
                        if (!"2".equals(appApi.getChangeStatus())) {
                            appApi.setId(null);
                            appApi.setValidStatus("1");
                            appApi.setApprovalEnv("1");
                            appApi.setExpSeq(opsForValue.get(EXP_SQE));
                            appApiService.save(appApi);
                        }
                    });
                    List<ProduceApplyVO> produceApplyList = produceApplyService.selectProApplyByAppId(newApp.getPid());
                    if (produceApplyList.size() > 0) {
                        //存在，更新
                        ProduceApplyVO produceApply = produceApplyList.get(0);
                        TestApply testApplys = testApplyService.selectByAppId(newApp.getPid());
                        produceApply.setIp(testApplys.getIp());
                        produceApplyService.saveOrUpdate(produceApply);
                    }
                } else {
                    if (isChange) {
                        List<ProduceApplyVO> produceApplyList = produceApplyService.selectProApplyByAppId(newApp.getPid());
                        if (produceApplyList.size() > 0) {
                            ProduceApplyVO produceApplyVO = produceApplyList.get(0);
                            produceApplyVO.setIsChange("1");
                            produceApplyService.updateById(produceApplyVO);
                        }
                    }
                }
                data.put("code", 200);
                data.put("msg", "审批成功");
            } else {
                data.put("code", 500);
                data.put("msg", "审批失败");
            }
        } else {
            // 审批拒绝
            oldApp.setId(newApp.getPid());
            oldApp.setAppState("2");
            oldApp.setApproveOpinion(approvalOpinion);
            boolean oldUpdated = appService.updateById(oldApp);
            newApp.setOperationType(2L);
            newApp.setStatus(2);
            newApp.setApproveOpinion(approvalOpinion);
            boolean newUpdated = appService.updateById(newApp);
            if (oldUpdated & newUpdated) {
                data.put("code", 200);
                data.put("msg", "审批成功");
            } else {
                data.put("code", 500);
                data.put("msg", "审批失败");
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void produceApplyChange(JSONObject data, String opinionType, String app_id, String approvalOpinion) {
        //应用申请生产环境
        ProduceApply produceApply = produceApplyService.getById(Long.parseLong(app_id));
        if (("1").equals(opinionType)) {
            //直接修改为审批已通过
            produceApply.setApproveStatus("1");
            produceApply.setIsChange("0");
            produceApply.setApproveStatus("1");
            produceApply.setChangeStatus(opinionType);
        } else {
            produceApply.setApproveStatus(opinionType);
            produceApply.setIsChange("1");
            produceApply.setApproveStatus("2");
            produceApply.setChangeStatus(opinionType);

        }
        produceApply.setApproveOpinion(approvalOpinion);
        produceApply.setApproveTime(DateUtils.asDate(LocalDateTime.now()));
        //删除移除状态的api
//        appApiService.deleteAppApiByAppId(produceApply.getAppId());
        ProduceApply oldProduceApply = produceApplyService.getById(produceApply.getPid());
        oldProduceApply.setIsChange("0");
        oldProduceApply.setChangeStatus(opinionType);
        if (produceApplyService.updateById(produceApply) && produceApplyService.updateById(oldProduceApply)) {
            data.put("code", 200);
            data.put("msg", "审批成功");
        } else {
            data.put("code", 500);
            data.put("msg", "审批失败");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void onlineApply(JSONObject data, String opinionType, String app_id, String approvalOpinion) {
        //应用上线
        OnlineApply onlineApply = onlineApplyService.getById(Long.parseLong(app_id));
        onlineApply.setApproveStatus(opinionType);
        onlineApply.setApproveTime(DateUtils.asDate(LocalDateTime.now()));
        onlineApply.setApproveOpinion(approvalOpinion);
        if (onlineApplyService.updateById(onlineApply)) {
            data.put("code", 200);
            data.put("msg", "审批成功");
        } else {
            data.put("code", 500);
            data.put("msg", "审批失败");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void produceApply(JSONObject data, String opinionType, String app_id, String approvalOpinion) {
        //应用申请生产环境
        ProduceApply produceApply = produceApplyService.getById(Long.parseLong(app_id));
        if (("1").equals(opinionType)) {
            //状态已审批
//            produceApply.setApproveStatus("6");
            //直接修改为审批已通过
            produceApply.setApproveStatus("1");
        } else {
            produceApply.setApproveStatus(opinionType);
        }
        produceApply.setApproveOpinion(approvalOpinion);
        produceApply.setApproveTime(DateUtils.asDate(LocalDateTime.now()));
        if (produceApplyService.updateById(produceApply)) {
            //增加生产环境渠道api关联数据  修改时间：20210702
            List<AppApi> lists = appApiService.selectByAppId(produceApply.getAppId());
            ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
            //先删除旧数据，然后插入新数据
            appApiService.deleteByAppId(produceApply.getAppId(), "1");
            lists.forEach(appApi -> {
                appApi.setId(null);
                appApi.setValidStatus("1");
                appApi.setApprovalEnv("1");
                appApi.setExpSeq(opsForValue.get(EXP_SQE));
                appApiService.save(appApi);
            });

            data.put("code", 200);
            data.put("msg", "审批成功");
        } else {
            data.put("code", 500);
            data.put("msg", "审批失败");
        }
        if (200 == data.getInt("code")) {
            // 申请生产环境成功调用 0代表生产
            App app = new App();
            // 20200812 修改为 渠道id
//                        app.setId(Long.parseLong(app_id));
            app.setId(produceApply.getAppId());
            app.setEnv(0L);
            appService.approvalCreateAppInfo(app);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void orgAccreditationChange(JSONObject data, String opinionType, String app_id, String approvalOpinion) {
        // 机构信息变更
        Orga newOrg = orgaService.getById(app_id);
        Orga oldOrg = new Orga();
        if (opinionType.equals("1")) {
            // 审批通过
            // 将变更最新数据copy到旧数据中并更新(下面为前台支持修改的信息)
            oldOrg.setId(newOrg.getParentId());
            oldOrg.setOfficialWeb(newOrg.getOfficialWeb());
            oldOrg.setOrgaType(newOrg.getOrgaType());
            oldOrg.setPostCode(newOrg.getPostCode());
            oldOrg.setServiceTrade(newOrg.getServiceTrade());
            oldOrg.setOrgaArea(newOrg.getOrgaArea());
            oldOrg.setOfficialLetter(newOrg.getOfficialLetter());
            oldOrg.setOtherFiles(newOrg.getOtherFiles());
            oldOrg.setPerCharge(newOrg.getPerCharge());
            oldOrg.setPerNumber(newOrg.getPerNumber());
            oldOrg.setAuthDocumentType(newOrg.getAuthDocumentType());
            oldOrg.setAuthDocumentNum(newOrg.getAuthDocumentNum());
            oldOrg.setInvoiceMailingAddr(newOrg.getInvoiceMailingAddr());
            boolean oldUpdated = orgaService.updateById(oldOrg);
            // 更改认证状态
            newOrg.setAuthFlag("1");
            newOrg.setApproveOpinion(approvalOpinion);
            boolean newUpdated = orgaService.updateById(newOrg);
            if (oldUpdated & newUpdated) {
                data.put("code", 200);
                data.put("msg", "审批成功");
            } else {
                data.put("code", 500);
                data.put("msg", "审批失败");
            }
        } else {
            // 审批拒绝
            newOrg.setAuthFlag("2");
            newOrg.setApproveOpinion(approvalOpinion);
            boolean newUpdated = orgaService.updateById(newOrg);
            if (newUpdated) {
                data.put("code", 200);
                data.put("msg", "审批成功");
            } else {
                data.put("code", 500);
                data.put("msg", "审批失败");
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void channelCreate(List<String> ids, JSONObject data, String opinionType, String app_id, String approvalOpinion) {
        // 应用创建
        App app = appService.getById(Long.parseLong(app_id));
        if ("1".equals(opinionType)) {
            //审批通过变为已审批
//            app.setStatus(6);
            //审批通过状态调整为已通过 修改时间：20210219 14:27
            app.setStatus(1);
            app.setAppStatus("1");
            //添加渠道权限
            List<Api> api = apiService.selectApiByAppId(app.getId());
            ArrayList<String> list = new ArrayList<>();
            for (Api apiData : api) {
                String apiScope = apiData.getApiScope();
                if (list.contains(apiScope)) {
                    continue;
                } else {
                    list.add(apiScope);
                }
            }
            String scopes = StringUtils.join(list, ",");
            app.setScope(scopes);
            app.setTestScope(scopes);
        } else {
            app.setAppStatus("0");
            app.setStatus(Integer.parseInt(opinionType));
        }
        app.setApproveOpinion(approvalOpinion);
        // 申请测试环境
        TestApply tApplyQuery = new TestApply();
        tApplyQuery.setAppId(Long.parseLong(app_id));
        TestApply testApply = testApplyService.getOne(Condition.getQueryWrapper(tApplyQuery));
        testApply.setApproveStatus(opinionType);
        testApply.setApproveOpinion(approvalOpinion);
        testApply.setApproveTime(DateUtils.asDate(LocalDateTime.now()));
        if (ids == null || ids.size() <= 0) {
            if (appService.updateById(app) && appService.updateOpc_app_api(Long.parseLong(app_id), opinionType) > 0 && testApplyService.updateById(testApply)) {
                data.put("code", 200);
                data.put("msg", "审批成功");
            } else {
                data.put("code", 500);
                data.put("msg", "审批失败");
            }
        } else {
            //如果只传部分API
            AppApi appApi = new AppApi();
            appApi.setOpcAppId(Long.parseLong(app_id));
            appApi.setValidStatus(opinionType);
            switch (opinionType) {
                case "1":
                    //如果通过
                    int i = 0;
                    Map<Long, Object> condition = new HashMap<Long, Object>();
                    for (String api_id : ids) {
                        appApi.setId(Long.parseLong(api_id));
                        i += appService.updateSingleOpc_app_api(appApi);
                        condition.put(Long.parseLong(api_id), "");
                    }
                    // 更新未通过api状态
                    List<AppApi> appApis = appService.listRelatedApi(Long.parseLong(app_id));
                    for (AppApi api : appApis) {
                        if (null == condition.get(api.getId())) {
                            api.setValidStatus("2");
                            appService.updateSingleOpc_app_api(api);
                        }
                    }
                    if (appService.updateById(app) && i >= ids.size()) {
                        data.put("code", 200);
                        data.put("msg", "审批成功");
                    } else {
                        data.put("code", 500);
                        data.put("msg", "审批失败");
                    }
                    break;
                case "2":
                    //如果不通过
                    if (appService.updateById(app) && appService.updateOpc_app_api(Long.parseLong(app_id), opinionType) > 0 && testApplyService.updateById(testApply)) {
                        data.put("code", 200);
                        data.put("msg", "审批成功");
                    } else {
                        data.put("code", 500);
                        data.put("msg", "审批失败");
                    }
                    break;
                default:
                    break;
            }
        }
        if (200 == data.getInt("code")) {
            // 申请测试环境成功调用 1代表测试
            app.setEnv(1L);
            //审批通过自动生成 appId
//            app.setStatus(1);
            if (null == app.getAppId()) {
                String appCode = serialNumberService.generateSerialNumberByModelCode("opc_app");
                app.setAppId(appCode);
                app.setTestAppId(appCode + "-T");
            }

            Orga orga = orgaService.getById(app.getOpcOrgaId());

            if (!"1".equals(orga.getProcessFlag())) {
                //流程简化未开启，走原有流程
                appService.approvalCreateAppInfo(app);
            } else {
                //流程简化开启，直接生产测试环境和生产环境公私钥
                appService.approvalCreateAppInfoProcess(app);
                //生产环境加一条数据----内容copy测试环境
                //先查询 存在就更新，不然就新增

                List<ProduceApplyVO> produceApplyList = produceApplyService.selectProApplyByAppId(Long.parseLong(app_id));
                if (produceApplyList.size() > 0) {
                    //存在，更新
                    ProduceApplyVO produceApply = produceApplyList.get(0);
                    testApply.setApproveStatus(opinionType);
                    ProduceApply produceApply2 = new ProduceApply();
                    BeanUtils.copyProperties(produceApply, produceApply2);
                    produceApply2.setApproveStatus(opinionType);
                    produceApply2.setIsChange("0");
                    produceApply2.setChangeStatus("1");
                    produceApply2.setIp(testApply.getIp());
                    produceApplyService.saveOrUpdate(produceApply2);
                } else {
                    ProduceApply produceApply = new ProduceApply();
                    testApply.setApproveStatus(opinionType);
                    BeanUtils.copyProperties(testApply, produceApply);
                    produceApply.setApproveStatus(opinionType);
                    produceApply.setIsChange("0");
                    produceApply.setChangeStatus("1");
                    produceApply.setIp(testApply.getIp());
                    produceApplyService.save(produceApply);
                }

                //生产变更创建数据
                List<AppApi> list = appApiService.selectByAppIdStatus(app_id, "1");
                ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
                list.forEach(appApi -> {
                    appApi.setId(null);
                    appApi.setValidStatus("1");
                    appApi.setApprovalEnv("1");
                    appApi.setExpSeq(opsForValue.get(EXP_SQE));
                    appApiService.save(appApi);
                });
            }
            // 应用创建成功调用
            SandboxCase sandboxCase = new SandboxCase();
            sandboxCase.setCaseName(app.getAppName() + "案例");
            sandboxCase.setOpcOrgaId(app.getOpcOrgaId());
            sandboxCase.setOpcAppId(app.getId());
            iSandboxCaseService.modifySandboxCase(sandboxCase);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void orgAccreditation(JSONObject data, String opinionType, String app_id, String approveOpinion) {
        //机构认证
        Orga orga = orgaService.getById(Long.parseLong(app_id));
        System.out.println(Long.parseLong(app_id));
        orga.setAuthFlag(opinionType);
        orga.setApproveOpinion(approveOpinion);
        if ("1".equals(opinionType)) {
            //审批通过 启用状态
            orga.setOrgaStatus("1");
        }
        if (orgaService.updateById(orga)) {
            data.put("code", 200);
            data.put("msg", "审批成功");
        } else {
            data.put("code", 500);
            data.put("msg", "审批失败");
        }
    }

    /**
     * @param executionId, appId, taskId
     * @return
     */
    public R delete(String executionId, String appId, String taskId) {
        char type = appId.charAt(0);
        Long id = Long.parseLong(appId.substring(1, appId.length()));
        // 业务流程分支判断
        if (type == 'a') {
            // 产品和API关联
            Product productDetail = productService.getById(id);
            if (productDetail != null) {
                return R.fail(2002, "存在关联数据无法删除！");
            }
        } else if (type == 'i') {
            // 机构认证
            Orga orga = orgaService.getById(id);
            if (orga != null) {
                return R.fail(2002, "存在关联数据无法删除！");
            }
        } else if (type == 'k') {
            // 机构变更
            Orga orga = orgaService.getById(id);
            if (orga != null) {
                return R.fail(2002, "存在关联数据无法删除！");
            }
        } else if (type == 'c') {
            // 应用创建
            App app = appService.getById(id);
            if (app != null) {
                return R.fail(2002, "存在关联数据无法删除！");
            }
        } else if (type == 'n') {
            // 应用申请上线
            OnlineApply oApplyDetail = onlineApplyService.getById(id);
            if (oApplyDetail != null) {
                return R.fail(2002, "存在关联数据无法删除！");
            }
        } else if (type == 'p') {
            // 机构变更
            App appDetail = appService.getById(id);
            if (appDetail != null) {
                return R.fail(2002, "存在关联数据无法删除！");
            }
        } else if (type == 'b') {
            // API 审批
            List<Api> apis = issueApiService.selectApisById(id);
            if (apis.size() >= 1) {
                return R.fail(2002, "存在关联数据无法删除！");
            }
        } else if (type == 'z') {
            // 产品下线
            Product productDetail = productService.getById(id);
            if (productDetail != null) {
                return R.fail(2002, "存在关联数据无法删除！");
            }
        } else if (type == 'y') {
            // API 下线
            Api apiDetail = apiService.getById(id);
            if (apiDetail != null) {
                return R.fail(2002, "存在关联数据无法删除！");
            }
        }
        try {
            int res = approveMapper.clearn(executionId);
//            JSONObject res = restTemplate.getForObject(workflow_base_url + "/api/workflow/processinstance/delete?processInstanceId=" + executionId, JSONObject.class);

            if (res == 1) {
                return R.success("删除成功");
            } else {
                return R.fail(2002, "删除失败");
            }
        } catch (Exception e) {
            log.error("删除脏数据异常：{}", e);
            return R.fail(2002, "删除异常");
        }
    }


    /**
     * @Author wangjinghan
     * @param: type
     * appId  对应 wf_task表中的appId
     * @return:
     * @date: 2021/2/20 16:59
     */
    @Override
    public R deleteRelated(String type, String appId) {
        TaskDto taskDto = new TaskDto();
        taskDto.setAppId(type + appId);

        switch (type) {
            case "i"://机构认证
                taskDto.setProcessKeys("org_accreditation");
                break;
            case "k"://机构变更
                taskDto.setProcessKeys("org_accreditation_change");
                break;
            case "c"://渠道申请
                taskDto.setProcessKeys("channel_create");
                break;
            case "p"://渠道变更
                taskDto.setProcessKeys("channel_create_change");
                break;
            case "b"://API发布
                taskDto.setProcessKeys("api_publish");
                break;
            case "y"://API下线
                taskDto.setProcessKeys("api_offline");
                break;
            case "a"://产品发布
                taskDto.setProcessKeys("product_publish");
                break;
            case "z"://产品下线
                taskDto.setProcessKeys("product_offline");
                break;
            case "m"://生产验证申请
                taskDto.setProcessKeys("produce_apply");
                break;
            case "n"://正式上线申请
                taskDto.setProcessKeys("online_apply");
                break;
            case "x"://生产验证申请变更
                taskDto.setProcessKeys("produce_apply_change");
                break;
            default:
                return R.fail("没有传类型！");

        }
        //删除工作流数据
        approveMapper.deleteRelated(taskDto);
        return R.success("删除成功");
    }

    /**
     * @param processStartDto
     * @return com.dhcc.bpm.common.json.JSONObject
     * @throws
     * @Description 执行任务
     * @Author xiafayu
     * @Date 2020/2/24 20:44
     **/
    @Override
    public JSONObject start(ProcessStartDto processStartDto) {
        JSONObject result = null;
        try {
            result = restTemplate.postForObject(workflow_base_url + "/api/workflow/processinstance/start", processStartDto, JSONObject.class);
            log.info("工作流执行任务返回结果：{}", result);
        } catch (Exception e) {
            log.error("执行审批任务异常：{}", e);
            return null;
        }
        return result;
    }

    /**
     * @param taskDto
     * @param isHistory
     * @return com.dhcc.bpm.common.json.JSONObject
     * @throws
     * @Description 查询任务
     * @Author xiafayu
     * @Date 2020/2/24 20:44
     **/
    @Override
    public JSONObject taskList(TaskDto taskDto, String isHistory) {
        JSONObject resp = null;
        try {
            resp = restTemplate.postForObject(workflow_base_url + "/api/workflow/task/" + isHistory + "askList", taskDto, JSONObject.class);
            log.info("工作流查询任务返回结果：{}", resp);
        } catch (Exception e) {
            log.error("查询任务异常：{}", e);
            return null;
        }
        if (resp != null && resp.getInt("code") == 200) {
            JSONObject data = resp.getObj("data");
            JSONObject.JSONArray records = data.getArr("records");
            if (records.size() > 0) {
                JSONObject.JSONArray newRecords = new JSONObject.JSONArray();
                for (int i = 0; i < records.size(); i++) {
                    JSONObject obj = (JSONObject) records.get(i);
                    String appId = obj.getStr("appId");
                    char type = appId.charAt(0);
                    Long id = Long.parseLong(appId.substring(1, appId.length()));
                    // 业务流程分支判断
                    if (type == 'a') {
                        // 产品和API关联
                        productListVo productDetail = productService.selectById(id);
                        if (productDetail == null) {
                            obj.put("param", "");
                        } else {
                            obj.put("param", productDetail);
                        }
                        newRecords.add(obj);
                    } else if (type == 'i') {
                        // 机构认证
                        Orga orga = new Orga();
                        orga.setId(id);
                        Orga orgaDetail = orgaService.getOne(Condition.getQueryWrapper(orga));
                        if (orgaDetail == null) {
                            obj.put("param", "");
                        } else {
                            obj.put("param", orgaDetail);
                        }
                        newRecords.add(obj);
                    } else if (type == 'k') {
                        // 机构变更
                        Orga orga = new Orga();
                        orga.setId(id);
                        Orga orgaDetail = orgaService.getOne(Condition.getQueryWrapper(orga));
                        if (orgaDetail == null) {
                            obj.put("param", "");
                        } else {
                            obj.put("param", orgaDetail);
                        }
                        newRecords.add(obj);
                    } else if (type == 'c') {
                        // 应用创建
                        App app = new App();
                        app.setId(id);
                        App appDeatil = appService.getOne(Condition.getQueryWrapper(app));
                        TestApply tApply = new TestApply();
                        tApply.setAppId(id);
                        TestApply tApplyDetail = testApplyService.getOne(Condition.getQueryWrapper(tApply));
                        if (appDeatil != null && tApplyDetail != null) {
                            AppVO appVO = new AppVO();
                            BeanUtils.copyProperties(appDeatil, appVO);
                            appVO.setTestApplyId(String.valueOf(tApplyDetail.getId()));
                            appVO.setTestBeginTime(tApplyDetail.getTestBeginTime());
                            appVO.setTestEndTime(tApplyDetail.getTestEndTime());
                            appVO.setApplyMsg(tApplyDetail.getApplyMsg());
                            obj.put("param", appVO);
                        } else {
                            obj.put("param", "");
                        }
                        newRecords.add(obj);
/*                        App app = new App();
                        app.setId(id);
                        App appDeatil = appService.getOne(Condition.getQueryWrapper(app));
                        if (appDeatil == null) {
                            obj.put("param", "");
                        } else {
                            obj.put("param", appDeatil);
                        }
                        newRecords.add(obj);*/
                    } /*else if (type == 'j') {
                        // 应用申请测试环境
                        TestApply tApply = new TestApply();
                        tApply.setId(id);
                        TestApply tApplyDetail = testApplyService.getOne(Condition.getQueryWrapper(tApply));
                        if (tApplyDetail == null) {
                            obj.put("param", "");
                        } else {
                            App app = new App();
                            app.setId(tApplyDetail.getAppId());
                            App appDetail = appService.getOne(Condition.getQueryWrapper(app));
                            if (appDetail == null) {
                                obj.put("param", "");
                            } else {
                                obj.put("param", appDetail);
                            }
                        }
                        newRecords.add(obj);
                    }*/ else if (type == 'm') {
                        // 应用申请生产环境
                        ProduceApply pApply = new ProduceApply();
                        pApply.setId(id);
                        ProduceApply pApplyDetail = produceApplyService.getOne(Condition.getQueryWrapper(pApply));
                        if (pApplyDetail == null) {
                            obj.put("param", "");
                        } else {
                            App app = new App();
                            app.setId(pApplyDetail.getAppId());
                            App appDetail = appService.getOne(Condition.getQueryWrapper(app));
                            if (appDetail == null) {
                                obj.put("param", "");
                            } else {
                                obj.put("param", appDetail);
                            }
                        }
                        newRecords.add(obj);
                    } else if (type == 'x') {
                        // 应用申请生产环境
                        ProduceApply pApply = new ProduceApply();
                        pApply.setId(id);
                        ProduceApply pApplyDetail = produceApplyService.getOne(Condition.getQueryWrapper(pApply));
                        if (pApplyDetail == null) {
                            obj.put("param", "");
                        } else {
                            App app = new App();
                            app.setId(pApplyDetail.getAppId());
                            App appDetail = appService.getOne(Condition.getQueryWrapper(app));
                            if (appDetail == null) {
                                obj.put("param", "");
                            } else {
                                obj.put("param", appDetail);
                            }
                        }
                        newRecords.add(obj);
                    } else if (type == 'n') {
                        // 应用申请上线
                        OnlineApply oApply = new OnlineApply();
                        oApply.setId(id);
                        OnlineApply oApplyDetail = onlineApplyService.getOne(Condition.getQueryWrapper(oApply));
                        if (oApplyDetail == null) {
                            obj.put("param", "");
                        } else {
                            App app = new App();
                            app.setId(oApplyDetail.getAppId());
                            App appDetail = appService.getOne(Condition.getQueryWrapper(app));
                            if (appDetail == null) {
                                obj.put("param", "");
                            } else {
                                obj.put("param", appDetail);
                            }
                        }
                        newRecords.add(obj);
                    } else if (type == 'p') {
                        // 机构变更
                        App appQuery = new App();
                        appQuery.setId(id);
                        App appDetail = appService.getOne(Condition.getQueryWrapper(appQuery));
                        if (appDetail == null) {
                            obj.put("param", "");
                        } else {
                            obj.put("param", appDetail);
                        }
                        newRecords.add(obj);
                    } else if (type == 'b') {
                        // API 审批
//                        Api apiQuery = new Api();
//                        apiQuery.setId(id);
//                        Api apiDetail = apiService.getOne(Condition.getQueryWrapper(apiQuery));
//                        if (apiDetail == null) {
//                            obj.put("param", "");
//                        } else {
//                            obj.put("param", apiDetail);
//                        }
                        List<Api> apis = issueApiService.selectApisById(id);
                        if (apis.size() <= 0) {
                            obj.put("param", "");
                        } else {
                            obj.put("param", apis);
                        }
                        newRecords.add(obj);
                    } else if (type == 'z') {
                        // 产品下线
                        Product productQuery = new Product();
                        productQuery.setId(id);
                        Product productDetail = productService.getOne(Condition.getQueryWrapper(productQuery));
                        if (productDetail == null) {
                            obj.put("param", "");
                        } else {
                            obj.put("param", productDetail);
                        }
                        newRecords.add(obj);
                    } else if (type == 'y') {
                        // API 下线
                        Api apiQuery = new Api();
                        apiQuery.setId(id);
                        Api apiDetail = apiService.getOne(Condition.getQueryWrapper(apiQuery));
                        if (apiDetail == null) {
                            obj.put("param", "");
                        } else {
                            obj.put("param", apiDetail);
                        }
                        newRecords.add(obj);
                    } else if (type == 'w') {
                        // 工单查询
                        WorkOrder workOrder = new WorkOrder();
                        workOrder.setId(id);
                        workOrder.setStatus(taskDto.getStatus());
                        workOrder.setType(taskDto.getType());
                        WorkOrder workOrderDetail = workOrderService.find(workOrder);
                        if (workOrderDetail == null) {
                            obj.put("param", "");
                            continue;
                        } else {
                            obj.put("param", workOrderDetail);
                        }
                        newRecords.add(obj);
                    } else {
                        obj.put("param", "");
                        newRecords.add(obj);
                    }
                }
                data.put("records", newRecords);
                resp.put("data", data);
                return resp;
            }
        }
        return resp;
    }

    @Override
    public String getNameById(JSONObject json) {
        String type = json.getStr("type");
        String id = json.getStr("id");
        if (id == null) {
            return null;
        }
        if ("api".equals(type)) {
            return apiService.getById(Long.valueOf(id)).getApiName();
        }
        if ("orga".equals(type)) {
            return orgaService.getById(Long.valueOf(id)).getOrgaName();
        }
        if ("chnl".equals(type)) {
            return appService.getById(Long.valueOf(id)).getAppName();
        }
        if ("prod".equals(type)) {
            return productService.getById(Long.valueOf(id)).getProductName();
        }
        if ("produceApply".equals(type)) {
            Long appId = produceApplyService.getById(Long.valueOf(id)).getAppId();
            return appService.getById(Long.valueOf(appId)).getAppName();
        }
        if ("onlineApply".equals(type)) {
            Long appId = onlineApplyService.getById(Long.valueOf(id)).getAppId();
            return appService.getById(Long.valueOf(appId)).getAppName();
        }
        return null;
    }

    /**
     * @param
     * @return void
     * @throws
     * @Description 刷新api配置
     * @Author xiafayu
     * @Date 2020/7/31 15:58
     **/
    @Override
    public void refreshApi(String id) {
        com.dhcc.bpm.modules.api.entity.Api api = apiService.getById(id);
        if (api != null) {
            String[] gatewayIds = api.getOpcGatewayId().split(",");
            String[] testGatewayIds = api.getOpcGatewayIdTest().split(",");
            for (String gatewayId : gatewayIds) {
                Gateway gateway = gatewayService.getById(gatewayId);
                sendMessage(gateway);
            }
            for (String testGatewayId : testGatewayIds) {
                Gateway gateway = gatewayService.getById(testGatewayId);
                sendMessage(gateway);
            }
        }

    }

    /**
     * 推送消息给网关
     *
     * @param gateway
     */
    private void sendMessage(Gateway gateway) {
        if (gateway != null) {
            String message = redisMessageSender.format(ConfigType.API.name(), "刷新接口配置");
            redisMessageSender.sendMessageToGateway(gateway.getGatewayCode(), message);
            String msg = redisMessageSender.format(ConfigType.RATELIMET.name(), "刷新接口限流配置");
            redisMessageSender.sendMessageToGateway(gateway.getGatewayCode(), msg);
            String route = redisMessageSender.format(ConfigType.ROUTE.name(), "刷新接口路由配置");
            redisMessageSender.sendMessageToGateway(gateway.getGatewayCode(), route);
        }
    }

    /**
     * @return void
     * @Description 刷新app配置
     * @Author xiafayu
     * @Date 2020/7/31 15:58
     **/
    @Override
    public void refreshApp(String id) {
        String msg = redisMessageSender.format(ConfigType.APPSECRET.name(), "刷新产品公私钥配置");
        redisMessageSender.sendMessageToGateway(null, msg);
        if (id != null) {
            App newApp = appService.getById(id);
            if (newApp != null) {
                refreshToken(newApp.getAppId());
                refreshToken(newApp.getTestAppId());
            }
        }
    }

    @Override
    public TaskDto findBytask(TaskDto taskDto) {
        return approveMapper.findBytask(taskDto);
    }

    public void refreshToken(String appId) {
        //刷新token
        Collection<OAuth2AccessToken> findTokensByClientId = tokenStore.findTokensByClientId(appId);
        findTokensByClientId.forEach(p -> redisMessageSender.sendMessageToChannel("TOKEN", tokenStore.readAccessToken(p.getValue()).getValue()));
    }
}
